package org.dxy.trigger.listener.workorder;

import com.google.common.eventbus.Subscribe;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.event.workorder.WorkOrderReleasedEvent;
import org.dxy.infrastructure.persistent.db.mybatispuls.po.query.WorkOrderViewPo;
import org.dxy.infrastructure.persistent.db.mybatispuls.service.WorkOrderViewService;
import org.dxy.trigger.listener.EventListener;
import org.springframework.stereotype.Component;

/**
 * @description: 监听工单下达事件，并更新工单读模型状态
 * @author: dxy
 * @createTime: 2025/8/4 22:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WorkOrderReleasedEventListener implements EventListener<WorkOrderReleasedEvent> {

    private final WorkOrderViewService workOrderViewService;

    /**
     * 处理工单下达事件
     * @param event 工单下达事件，包含工单ID等信息
     */
    @Override
    @Subscribe
    public void onEvent(WorkOrderReleasedEvent event) {
        log.info("接收到工单下达事件, event：{}", event.toString());
        
        WorkOrderViewPo workOrderViewPo = new WorkOrderViewPo();
        workOrderViewPo.setId(event.workOrderId())
                .setStatus(event.workOrderStatus());
        
        boolean updated = workOrderViewService.updateById(workOrderViewPo);
        if (updated) {
            log.info("工单下达状态更新成功，工单ID={}", event.workOrderId());
        } else {
            log.warn("工单下达状态更新失败，工单ID={}", event.workOrderId());
        }
    }
}